package com.heima.wemedia.service.impl;

import com.heima.common.enums.TaskTypeEnum;
import com.heima.feign.client.ScheduleClient;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wmnews.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {
    // 调接口
    @Autowired
    private ScheduleClient scheduleClient;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;
    /**
     * 添加任务到延迟队列中
     * @param id          文章的id
     * @param publishTime 发布的时间  可以做为任务的执行时间
     */
    @Override
    @Async // 异步线程执行
    public void addNewsToTask(Integer id, Date publishTime) {
        Task task = new Task();
        task.setExecuteTime(publishTime.getTime());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        // 封装自媒体文章信息
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        task.setParameters(ProtostuffUtil.serialize(wmNews)); // 使用第三方编译的二进制
        log.info("添加任务到延迟服务中");
        scheduleClient.addTask(task);
    }

    /**
     * 消费延迟队列数据
     */
    @Override
    @Scheduled(fixedRate = 50000)//设置为50s，要不时间太短
    @SneakyThrows
    public void scanNewsByTask() {
        log.info("文章审核-消费任务执行开始");
        //1.拉取任务
        Task task = scheduleClient.poll(
                TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority()
        );
        if(task != null && task.getParameters().length>0){
            byte[] bytes = task.getParameters();
            //反序列化
            WmNews wmNews = ProtostuffUtil.deserialize(bytes, WmNews.class);
            //2.调用自动审核业务存储数据到article表
            Integer newsId = wmNews.getId();
            wmNewsAutoScanService.autoScanWmNews(newsId); // 文章自动审核
        }
        log.info("文章审核消费任务执行结束");
    }
}
